package org.example.seckill.rabbitmq.seckill;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.seckill.bean.SeckillMsg;
import org.example.seckill.bean.User;
import org.example.seckill.bean.goods;
import org.example.seckill.bean.order;
import org.example.seckill.config.RabbitMqSeckillConfig;
import org.example.seckill.service.seckillOrderService;
import org.example.seckill.vo.orderStatus;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author woopsion
 * @date 2025-07-05
 */
@Service
@Slf4j
public class SeckillMsgReceiver {
    @Autowired
    private seckillOrderService sos;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 将msg 转成了 seckillMsg类型 目的是将封装的信息交给秒杀操作方法中
     * 异步进行秒杀
     * @param msg
     */
    @RabbitListener(queues = {RabbitMqSeckillConfig.QUEUE})
    public void receiveSeckillMsg(String msg){
        log.info("receiveSeckillMsg 接收消息"+msg);
        SeckillMsg seckillMsg = 
                JSONUtil.toBean(msg, SeckillMsg.class);
        orderStatus orderStatus = sos.doSeckill(seckillMsg.getUser(), seckillMsg.getGoods(), seckillMsg.getSeckillGoods());
        User user = seckillMsg.getUser();
        goods goods = seckillMsg.getGoods();
        //更新订单状态
        order o = (order)redisTemplate.opsForValue().get("order:detail:+" + user.getId()+ ":"
                    + goods.getId());
        o.setStatus(orderStatus.getStatus());
        redisTemplate.opsForValue().set("order:detail:+" + user.getId()+ ":"
                    + goods.getId(),o);
    }
}
